package artid.com.arttogoa;

import java.io.File;
import org.apache.commons.lang3.StringUtils;
import org.xutils.x;
import org.xutils.common.Callback.CommonCallback;
import org.xutils.http.RequestParams;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import artid.com.arttogoa.barcode.Cache;
import artid.com.arttogoa.util.AlertUtils;
import artid.com.arttogoa.util.AppUtil;
import artid.com.arttogoa.util.BitmapUtil;
import artid.com.arttogoa.util.CameraUtils;
import artid.com.arttogoa.util.NetUtils;
import artid.com.arttogoa.util.ToastUtil;
import artid.com.arttogoa.util.VioceUtils;
import artid.com.arttogoa.volley.VolleyBasic;

/**
 * 
 *    
 * 项目名称：ArtworkArtA   
 * 类名称：ReleaseDynamicActivity   
 * 类描述：发布动态   
 * 创建人：耿卫斌  
 * 创建时间：2016年5月16日 下午2:34:46      
 *
 */
public class ReleaseDynamicActivity extends BaseActivity implements
OnClickListener {
	private TextView mRelease;
	private EditText name, content;
	private ImageView releasephoto,showPic;
	String path;;
	Uri imgUri;
	Boolean isSetPic = false;
	RelativeLayout addimg;
	AlertDialog alertDialog;
	private String PhotoPath;//剪裁之后的图片路径
	private Bitmap clipBitmap;//剪裁之后的图片
	private String Bitmap64;//剪裁之后的图片流
	ImageView imgVoice;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_release_dynamic);
		initView();
	}

	private void initView() {
		mContext = this;
		imgVoice = (ImageView)findViewById(R.id.iv_vioce);
		imgVoice.setOnClickListener(this);
		path = Environment.getExternalStorageDirectory() + "/pintu" + "ti.jpg";
		File file = new File(path);
		if (file.exists())
			file.delete();
		mTittle = (TextView) findViewById(R.id.title_text);
		mTittle.setText("发布动态");
		setBack();
		mReleaseIcon = (ImageView) findViewById(R.id.release_icon);
		mReleaseIcon.setVisibility(View.VISIBLE);
		mReleaseIcon.setOnClickListener(this);
		mRelease = (TextView) findViewById(R.id.release_btn);
		mRelease.setOnClickListener(this);
		name = (EditText) findViewById(R.id.dynamic_release_name);
		content = (EditText) findViewById(R.id.dynamic_release_content);
		releasephoto = (ImageView) findViewById(R.id.add_img);
		releasephoto.setOnClickListener(this);
		addimg = (RelativeLayout) findViewById(R.id.add_img_layout);
		addimg.setOnClickListener(this);
		showPic = (ImageView)findViewById(R.id.image_showpic);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_vioce:
			VioceUtils vu = new VioceUtils(ReleaseDynamicActivity.this, imgVoice, content);
			vu.init();
			break;
		case R.id.release_btn:
			submit();
			break;
		case R.id.add_img_layout:
			showPopupWindow();
			break;
		case R.id.add_img:
			showPopupWindow();
			break;
		case R.id.release_icon:
			alertDialog = AlertUtils.showConsultaDialog(
					ReleaseDynamicActivity.this,
					ReleaseDynamicActivity.this.getWindowManager()
					.getDefaultDisplay().getWidth(),
					new OnClickListener() {
						@Override
						public void onClick(View view) {
							// TODO Auto-generated method stub
							switch (view.getId()) {
							case R.id.imageView2:
								alertDialog.dismiss();
								break;
							default:
								break;
							}
						}
					});
			break;
		default:
			break;
		}

	}

	// 点击头像，选择照片
	public void showPopupWindow() {
		AlertUtils.initPhotoAlertDialog(mContext,Integer.parseInt(NetUtils.getDisplayMetrics(ReleaseDynamicActivity.this).get(NetUtils.DM_WIDTH)), new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				switch (v.getId()) {
				case R.id.tv_phone:
					//检查权限
					if (ContextCompat.checkSelfPermission(ReleaseDynamicActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
						displayFrameworkBugMessageAndExit();
						return;
					}
					//照相机	
					CameraUtils.openCameraImage(ReleaseDynamicActivity.this);
					AlertUtils.dismiss();
					break;
				case R.id.tv_choice:
					//从相册获取
					CameraUtils.openLocalImage(ReleaseDynamicActivity.this);
					AlertUtils.dismiss();
					break;
				default:
					break;
				}
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
		// TODO Auto-generated method stub  
		super.onActivityResult(requestCode, resultCode, data);  
		if (requestCode == CameraUtils.GET_IMAGE_BY_CAMERA) {
			final Uri uri=CameraUtils.imageUriFromCamera;
			if(uri != null) {
				Intent i=new Intent(mContext,Clip_Activity.class);
				i.putExtra("ImagePath",  BitmapUtil.UriConversionAbsoluteURL(mContext, uri));
				startActivityForResult(i, 200);
			}else{
				//防止文件不会立马创建
				new Handler().postDelayed(new Runnable() {
					@Override
					public void run() {
						if(uri != null) {
							Intent i=new Intent(mContext,Clip_Activity.class);
							i.putExtra("ImagePath", BitmapUtil.UriConversionAbsoluteURL(mContext, uri));
							startActivityForResult(i, 200);
						}
					}
				}, 1000);
			}
		} else if (requestCode == CameraUtils.GET_IMAGE_FROM_PHONE) {
			//判断是否从相册中获取图片
			if (data != null) {
				// 得到图片的全路径
				Uri uri = data.getData();
				Intent i=new Intent(mContext,Clip_Activity.class);
				i.putExtra("ImagePath", BitmapUtil.UriConversionAbsoluteURL(mContext, uri));
				startActivityForResult(i, 200);
			}
		} else if(requestCode==200){
			//获取剪切后的图片路径
			if(data!=null){
				PhotoPath=data.getExtras().getString("PhotoPath");  
				if(!StringUtils.isEmpty(PhotoPath)){
					clipBitmap=BitmapUtil.getSmallBitmap(PhotoPath, 500, 500);
					//设置图片
					showPic.setImageBitmap(clipBitmap);
					showPic.setVisibility(View.VISIBLE);

					Bitmap64= BitmapUtil.bitmaptoString(clipBitmap);

				}
			}
		}
	}

	// /**
	// * 裁剪图片方法实现
	// *
	// * @param uri
	// */
	// public void startPhotoZoom(Uri uri) {
	// Intent intent = new Intent("com.android.camera.action.CROP");
	// intent.setDataAndType(uri, "image/*");
	// // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
	// intent.putExtra("crop", "true");
	// // aspectX aspectY 是宽高的比例
	// intent.putExtra("aspectX", 1);
	// intent.putExtra("aspectY", 1);
	// // outputX outputY 是裁剪图片宽高
	// intent.putExtra("outputX", 330);
	// intent.putExtra("outputY", 330);
	// intent.putExtra("return-data", true);
	// startActivityForResult(intent, 4);
	// }


	private void submit() {
		if (TextUtils.isEmpty(name.getText().toString())) {
			Toast.makeText(mContext, "请输入动态名称~", 2).show();
			return;
		} else if (TextUtils.isEmpty(content.getText().toString())) {
			Toast.makeText(mContext, "请输入动态描述~", 2).show();
			return;
		}
		if (TextUtils.isEmpty(Bitmap64)) {
			Toast.makeText(mContext, "请选择动态图片~", 2).show();
			return;
		}
		VolleyBasic.showLoding(mContext);
		RequestParams params=new RequestParams(Cache.artworkrelease);
		params.addHeader("Accept",  "application/json, text/javascript, */*");
		params.addParameter("token", AppUtil.getUser().getToken());
		params.addParameter("title", name.getText().toString());
		params.addParameter("imgdata", Bitmap64);
		params.addParameter("detail", content.getText().toString());
		x.http().post(params, new CommonCallback<String>() {

			@Override
			public void onCancelled(CancelledException cex) {
				// TODO Auto-generated method stub
				System.out.println("主动停止网络请求");
			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {
				// TODO Auto-generated method stub
				//请求错误
				if(isOnCallback==false){
					//ex异常信息不是来自回调方法
					System.out.println("ex异常信息不是来自回调方法："+ex.getMessage());
				}else{
					//ex异常信息是来自回调方法
					System.out.println("ex异常信息是来自回调方法："+ex.getMessage());
				}
				VolleyBasic.disMissLoding();
			}

			@Override
			public void onFinished() {
				// TODO Auto-generated method stub
				
				System.out.println("请求完毕,不管成功失败");
			}

			@Override
			public void onSuccess(String result) {
				// TODO Auto-generated method stub
				//成功
				new Handler().postDelayed(new Runnable() {
					@Override
					public void run() {
						if(!StringUtils.isEmpty(PhotoPath)){
							BitmapUtil.deleteBitmap(PhotoPath);
						}
						ToastUtil.toast(mContext, "发布成功");
						Intent intent0 = new Intent("com.ArtDynamicActivity.receiver");  
						intent0.putExtra("isRefresh", true);
						mContext.sendBroadcast(intent0);
						VolleyBasic.disMissLoding();
						finish();
					}
				}, 2000);
			}
		});
	}

	/**
	 * 若摄像头被占用或者摄像头有问题则跳出提示对话框
	 */
	private void displayFrameworkBugMessageAndExit() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getString(R.string.app_name));
		builder.setMessage("请设置开启摄像头权限");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				NetUtils.getAppDetailSettingIntent(mContext);
			}
		});
		builder.show();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		VolleyBasic.disMissLoding();
	}

}
